package com.wan.nettyproject;

import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;

public class MainActivity extends Activity implements View.OnClickListener {
    private TextView tv_title;
    private EditText et_content;
    private Button btn_send;
    private ListView lv_chat;
    private String from, to;
    private ArrayList<MessageEnty> datas;
    private ChatAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        from = getIntent().getStringExtra("from");
        to = getIntent().getStringExtra("to");
        initUI();
        datas = new ArrayList<>();
        adapter = new ChatAdapter(MainActivity.this, datas);
        lv_chat.setAdapter(adapter);
        EventBus.getDefault().register(this);
    }

    private void initUI() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        et_content = (EditText) findViewById(R.id.et_content);
        btn_send = (Button) findViewById(R.id.btn_send);
        lv_chat = (ListView) findViewById(R.id.lv_chat);

        tv_title.setText("我是" + from + " 对方是" + to);
        btn_send.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_send:
                clickSend();
                break;
        }
    }

    private void clickSend() {
        MessageEnty messageEnty = new MessageEnty();
        messageEnty.setFrom(from);
        messageEnty.setTo(to);
        messageEnty.setContent(et_content.getText().toString());
        //datas.add(messageEnty);
        SocketManager.instance().sendRequest(messageEnty);
        et_content.setText("");
        //adapter.notifyDataSetChanged();
    }
    public void onEventMainThread(MessageEvent event) {
        switch (event.event) {
            case MESSAGE_ACCEPT:
                Log.e("test","收到了新消息");
                datas.add(event.entity);
                adapter.notifyDataSetChanged();
                break;
        }
    }
}
